<?php
// Ticket Plugin for SiT (Support Incident Tracker)
// Copyright (C) 2000-2008 Salford Software Ltd. and Contributors
//
// This software may be used and distributed according to the terms
// of the GNU General Public License, incorporated herein by reference.
//
// Authors: Ouedarbi mohamed <moms_killer[at]hotmail.com>

$ticket_version = $PLUGININFO['ticket']['version'];

/*****************************************************
TICKET ADD
*****************************************************/
/**
 * Generates a HTML drop down of Location as Site within SiT!
 * @param string $name The name of the field
 * @param int $id The ID of the selected item
 * @param bool $required Whether this is a mandetory field, defaults to false
 * @param bool $showinactive Whether to show the sites marked inactive, defaults to false
 * @return string The HTML for the drop down
 */
function location_drop_down($name, $id, $required = FALSE, $showinactive = FALSE)
{
    global $dbSites, $strEllipsis;
    $sql  = "SELECT id, name, department FROM `{$dbSites}` ";
    if (!$showinactive)  $sql .= "WHERE active = 'true' ";
    $sql .= "ORDER BY name ASC";
    $result = mysql_query($sql);

    $html = "<select name='{$name}'";
    if ($required)
    {
        $html .= " class='required' ";
    }
    $html .= "onChange=change_location(this.form)>\n";
    if ($id == 0)
    {
        $html .="<option selected='selected' value='0'></option>\n";
    }

    while ($sites = mysql_fetch_object($result))
    {
        $text = $sites->name;
        if (!empty($sites->department))
        {
            $text.= ", ".$sites->department;
        }

        if (strlen($text) >= 55)
        {
            $text = mb_substr(trim($text), 0, 55, 'UTF-8').$strEllipsis;
        }
        else
        {
            $text = $text;
        }

        $html .= "<option ";
        if ($sites->id == $id)
        {
            $html .= "selected='selected' ";
        } 

        $html .= "value='{$_SERVER['PHP_SELF']}?location={$sites->id}'>{$text}</option>\n";
    }
    $html .= "</select>\n";

    return $html;
}


/*
 * prints the HTML for a drop down list of contacts, with the given name
 * and with the given id only from a specifique site ($location).
 * Located in add_incident
 * @author Ivan Lucas modified by Ouedarbi mohamed
 */
function contactuser_drop_down($name, $id, $showsite = FALSE, $required = FALSE, $location)
{
    global $dbContacts, $dbSites;
	if (!$location)
	{$location = "1";}

    if ($showsite)
    {
        $sql  = "SELECT c.id AS contactid, s.id AS siteid, surname, forenames, ";
        $sql .= "s.name AS sitename, s.department AS department, c.department AS service ";
        $sql .= "FROM `{$dbContacts}` AS c, `{$dbSites}` AS s WHERE c.siteid = s.id  AND s.id = $location AND c.active = 'true' ";
        $sql .= "AND s.active = 'true' ";
        $sql .= "ORDER BY  surname ASC, forenames ASC, c.department ASC";
    }
    else
    {
        $sql  = "SELECT c.id AS contactid, surname, forenames FROM `{$dbContacts}` AS c, `{$dbSites}` AS s ";
        $sql .= "WHERE c.siteid = s.id AND s.active = 'true' AND c.active = 'true' ";
        $sql .= "ORDER BY  forenames ASC, surname ASC";
	}

    $result = mysql_query($sql);
    if (mysql_error()) trigger_error(mysql_error(),E_USER_WARNING);


 

    $html = "<select name='$name' id='$id'>\n";
    // if ($required)
    // {
        // $html .= " class='required' ";
    // }
    // $html .= "onChange=change_contact(this.form)>\n";
    if ($id == 0)
    {
        $html .= "<option selected='selected' value='0'></option>\n";
    }

    $prevsite=0;
    while ($contacts = mysql_fetch_object($result))
    {
        if ($showsite AND $prevsite != $contacts->siteid AND $prevsite != 0)
        {
            $html .= "</optgroup>\n";
        }

        if ($showsite AND $prevsite != $contacts->siteid)
        {
            $html .= "<optgroup label='".htmlentities($contacts->sitename, ENT_COMPAT, 'UTF-8').", ".htmlentities($contacts->department, ENT_COMPAT, $GLOBALS['i18ncharset'])."'>";
        }

        $realname = "{$contacts->surname} {$contacts->forenames} ({$contacts->service}) ";
        $html .= "<option ";
        if ($contacts->contactid == $id)
        {
            $html .= "selected='selected' ";
        }
        // $html .= "value='{$_SERVER['PHP_SELF']}?location=$location&contactid={$contacts->contactid}'><b>{$realname}</b>";
 
        $html .= "value='{$contacts->contactid}'><b>{$realname}</b>"; $html .= "</option>\n";

        $prevsite = $contacts->siteid;
    }
    if ($showsite)
    {
        $html.= "</optgroup>";
    }

    $html .= "</select>\n";
    return $html;
}

/**
* Output html for the 'Date Needed By' box
* Used in add incident and update incident
 * @param string $formid. HTML ID of the form containing the controls
* @return $html string html to output
* @author Kieran Hogg
* @TODO populate $id
*/
function date_needed_by($formid)
{
    global $now, $strAM, $strPM;
	
    $html = "<label>{$GLOBALS['strToBeDoneFor']}</label><br />\n";	
    $html .= "<input name='needed_by' id='needed_by' size='10' value='{$needed_by}' />";
    $html .= date_picker("{$formid}.needed_by");
    $html .= " <select name='timeoffset' id='timeoffset' >";
    $html .= "<option value='0'></option>";
    $html .= "<option value='0'>8:00 $strAM</option>";
    $html .= "<option value='1'>9:00 $strAM</option>";
    $html .= "<option value='2'>10:00 $strAM</option>";
    $html .= "<option value='3'>11:00 $strAM</option>";
    $html .= "<option value='4'>12:00 $strPM</option>";
    $html .= "<option value='5'>1:00 $strPM</option>";
    $html .= "<option value='6'>2:00 $strPM</option>";
    $html .= "<option value='7'>3:00 $strPM</option>";
    $html .= "<option value='8'>4:00 $strPM</option>";
    $html .= "<option value='9'>5:00 $strPM</option>";
    $html .= "</select>";

    return $html;
}

/**
  * Uses scriptaculous and AutoComplete.js to make a form text input
  * box autocomplete
  * @author Ivan Lucas
  * @param string $formelement. form element id, eg. textinput
  * @param string $action. ajaxdata.php action to return JSON data
  * @returns string HTML javascript block
  * @note The page that calls this function MUST include the required
  * javascript libraries. e.g.
  *   $pagescripts = array('scriptaculous/scriptaculous.js','AutoComplete.js');
*/
function ticket_autocomplete($formelement, $action='autocomplete_sitecontact' )
{
    $html .= "<script type=\"text/javascript\">\n//<![CDATA[\n";
    // Disable browser autocomplete (it clashes)
    $html .= "$('$formelement').setAttribute(\"autocomplete\", \"off\"); \n";
    $html .= "new AutoComplete('{$formelement}', 'ajaxdata.php?action={$action}&s=', {\n";
    $html .= "delay: 0.25,\n";
    $html .= "resultFormat: AutoComplete.Options.RESULT_FORMAT_JSON\n";
    $html .= "}); \n//]]>\n</script>\n";

    return $html;
}
function hi_autocomplete($formelement, $action='hardware' )
{
    $html .= "<script type=\"text/javascript\">\n//<![CDATA[\n";
    // Disable browser autocomplete (it clashes)
    $html .= "$('$formelement').setAttribute(\"autocomplete\", \"off\"); \n";
    $html .= "new AutoComplete('{$formelement}', 'ajaxdata.php?action={$action}&s=', {\n";
    $html .= "delay: 0.25,\n";
    $html .= "resultFormat: AutoComplete.Options.RESULT_FORMAT_JSON\n";
    $html .= "}); \n//]]>\n</script>\n";

    return $html;
}

/**
    * Return a contacts department
    * @author Ivan Lucas
    * @param integer $id. Contact ID
    * @returns string. Department
*/
function contact_department($id)
{
    return db_read_column('department', $GLOBALS['dbContacts'], $id);
}

/**
    * Return a contacts county
    * @author Ivan Lucas
    * @param integer $id. Contact ID
    * @returns string. Department
*/
function contact_county($id)
{
    return db_read_column('county', $GLOBALS['dbSites'], $id);
}

/**
* Output html for the 'incident option' box
* Used in add ticket and update ticket
 * @param string $formid. HTML ID of the form containing the controls
* @return $html string html to output
* @author Kieran Hogg modified byOuedarbi Mohamed
* @TODO populate $id
*/
function incident_option($formid)
{

    $html = "{$GLOBALS['strIncidentOption']}".help_link('IncidentOption')."<br />";
    $html .= "<label>";
    $html .= "<input checked='checked' type='radio' name='incident_option' ";
    $html .= "id='ttna_none' onchange=\"update_io();\" onclick=\"this.blur();\" ";
	$html .= " value='none' />{$GLOBALS['strNone']}";
    $html .= "</label><br />";
    $html .= "<label><input type='radio' name='incident_option' ";
    $html .= "id='ttna_waiting' value='waiting' onchange=\"update_io();\" onclick=\"this.blur();\" />";
    $html .= "{$GLOBALS['strWaitingIncident']}</label><br />\n";
    $html .= "<span id='ttnawaiting'";
    if (empty($na_days) AND
        empty($na_hours) AND
        empty($na_minutes))
    {
        $html .= " style='display: none;'";
    }
    $html .= ">";
    $html .= "\n</span>";
    $html .= "<label><input type='radio' name='incident_option' id='ttna_solution' ";
    $html .= "value='solution' onchange=\"update_io();\" onclick=\"this.blur();\" />";
    $html .= "{$GLOBALS['strExpressIncident']}</label><br />\n";
    $html .= "<div id='ttnasolution' style='display: none;'>";
    $html .= "<b>{$GLOBALS['strSolution']}</b>";
	$html .="<br><br><textarea id='solution' name='solution' cols='40' rows='3' ></textarea><br/><br/>";
	$html .= closingstatus_drop_down("closingstatus", 0, TRUE);
    $html .= "<br />\n</div>";
    return $html;
}

/*************
TICKETS.PHP  *
**************/
function ticket_get_next_target($incidentid)
{
    global $now;
    // Find the most recent SLA target that was met
    $sql = "SELECT u.sla, u.timestamp, t.date_neededby FROM `{$GLOBALS['dbUpdates']}` AS u, `{$GLOBALS['dbTicket']}` AS t WHERE u.incidentid='{$incidentid}' AND type='slamet' AND t.incidentid='{$incidentid}' ORDER BY u.id DESC LIMIT 1";
    $result = mysql_query($sql);
    if (mysql_error()) trigger_error(mysql_error(),E_USER_WARNING);

    $target = '';
    if (mysql_num_rows($result) > 0)
    {
        $upd = mysql_fetch_object($result);
        switch ($upd->sla)
        {
            case 'opened':
                $target->type = 'initialresponse';
				// $target->since = calculate_incident_working_time($incidentid, $upd->timestamp, $now);
                break;
            case 'initialresponse':
                $target->type = 'probdef';
				// $target->since = calculate_incident_working_time($incidentid, $upd->timestamp, $now);
                break;
            case 'probdef':
                $target->type = 'actionplan';
				// $target->since = calculate_incident_working_time($incidentid, $upd->timestamp, $now);
                break;
            case 'actionplan':
                $target->type = 'solution';
				// $target->since = calculate_incident_working_time($incidentid, $upd->timestamp, $now);
                break;
            case 'solution':
                $target->type = '';
				// $target->since = calculate_incident_working_time($incidentid, $upd->timestamp, $now);
                break;
            case 'closed':
                $target->type = 'opened';
				// $target->since = calculate_incident_working_time($incidentid, $upd->timestamp, $now);
                break;
            case 'planned':
                $target->type = 'date_needed_by';
				$target->t1 = $upd->date_neededby;
				$target->timestamp = $upd->timestamp;
				$target->since1 = calculate_incident_working_time($incidentid, $upd->timestamp, $now);
				$target->since_neededby = calculate_incident_working_time($incidentid, $upd->timestamp, $upd->date_neededby);				
				$target->neededby = ($target->since_neededby - $target->since1) ;
                break;
        }

         $target->since = calculate_incident_working_time($incidentid, $upd->timestamp, $now);
    }
    else
    {
        $target->type = 'regularcontact';
        $target->since = 0;
    }
    return $target;
}

function ticket_target_type_name($targettype)
{
    switch ($targettype)
    {
        case 'opened':
            $name = $GLOBALS['strOpened'];
            break;
        case 'initialresponse':
            $name = $GLOBALS['strInitialResponse'];
            break;
        case 'probdef':
            $name = $GLOBALS['strProblemDefinition'];
            break;
        case 'actionplan':
            $name = $GLOBALS['strActionPlan'];
            break;
        case 'solution':
            $name = $GLOBALS['strResolutionReprioritisation'];
            break;
        case 'closed':
            $name = '';
            break;
        case 'regularcontact':
            $name = '';
            break; // Contact Customer
/******************************************************************************************************/			
        case 'date_needed_by':
            $name = 'Panification';
            break; 
/********************************************************************************************************/			
        default:
            $name = '';
            break;
    }
    return $name;
}

/**
 * Return a string containing the time remaining as working days/hours/minutes (eg. 9am - 5pm)
 * @author Ivan Lucas
 * @returns string. Length of working time, in readable days, hours and minutes
 * @note The working day is calculated using the $CONFIG['end_working_day'] and
 * $CONFIG['start_working_day'] config variables
 */
function ticket_format_workday_minutes($minutes)
{
    global $CONFIG, $strXMins, $strMin, $strXHs, $strXH;
    global $strTicketXWorkingDay, $strTicketXWorkingDays;
    $working_day_mins = ($CONFIG['end_working_day'] - $CONFIG['start_working_day']) / 60;
    $days = floor($minutes / $working_day_mins);
    $remainder = ($minutes % $working_day_mins);
    $hours = floor($remainder / 60);
    $minutes = floor($remainder % 60);

    if ($days == 1)
    {
        $time = sprintf($strTicketXWorkingDay, $days);
    }
    elseif ($days > 1)
    {
        $time = sprintf($strTicketXWorkingDays, $days);
    }

    if ($days <= 3 AND $hours == 1)
    {
        $time .= " ".sprintf($strXH, $hours);
    }
    elseif ($days <= 3 AND $hours > 1)
    {
        $time .= " ".sprintf($strXHs, $hours);
    }
    elseif ($days > 3 AND $hours >= 1)
    {
        $time = "&gt; ".$time;
    }

    if ($days < 1 AND $hours < 8 AND $minutes == 1)
    {
        $time .= " ".$strMin;
    }
    elseif ($days < 1 AND $hours < 8 AND $minutes > 1)
    {
        $time .= " ".sprintf($strXMins, $minutes);
    }

    if ($days == 1 AND $hours < 8 AND $minutes == 1)
    {
        $time .= " ".$strMin;
    }
    elseif ($days == 1 AND $hours < 8 AND $minutes > 1)
    {
        $time .= " ".sprintf($strXMins, $minutes);
    }

    $time = trim($time);

    return $time;
}
?>